//
//  HYFileDownloadViewCell.m
//  XPlayer
//
//  Created by liguoqing on 2023/10/12.
//

#import "HYFileDownloadViewCell.h"
#import "HYFileDownloadItemViewModel.h"
#import <HYUtls/CommUtls+NSInteger.h>
#import "HYFiledownloadTool.h"

@interface HYFileDownloadViewCell ()

@property (nonatomic, strong) UIImageView *fileImgeView;

@property (nonatomic, strong) UIImageView *markView;

@property (nonatomic, strong) UILabel *titleLabel;

@property (nonatomic, strong) UIImageView *downCompleteImageView;

@property (nonatomic, strong) UIProgressView *progressView;

@property (nonatomic, strong) UIImageView *pauseImgView;

@property (nonatomic, strong) UIButton *pauseBtn;

@property (nonatomic, strong) UILabel *speedLabel;

@property (nonatomic, strong) UILabel *sizeLabel;
// 下载进度
@property (nonatomic, assign) CGFloat progress;
// 已下载大小
@property (nonatomic, strong) NSString *donwnloadSize;
// 接收到的字节
@property (nonatomic, assign) long long intervalFileSize;
// 上次计算速度时的时间戳
@property (nonatomic, assign) NSTimeInterval lastSpeedTime;
// 下载失败
@property (nonatomic, assign) NSInteger errorCode;

@property (nonatomic, strong) HYFileDownloadItemViewModel *itemVM;

@end

@implementation HYFileDownloadViewCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if(self){
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        [self configUI];
    }
    return self;
}

- (void)configUI
{
    self.contentView.backgroundColor = AppContentBgThemeColor;
    [self.contentView addSubview:self.fileImgeView];
    [self.fileImgeView addSubview:self.markView];
    [self.contentView addSubview:self.pauseImgView];
    [self.contentView addSubview:self.pauseBtn];
    [self.contentView addSubview:self.titleLabel];
    [self.contentView addSubview:self.downCompleteImageView];
    [self.contentView addSubview:self.progressView];
    [self.contentView addSubview:self.speedLabel];
    [self.contentView addSubview:self.sizeLabel];
    [self.fileImgeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.top.mas_equalTo(5);
        make.bottom.mas_equalTo(-5);
        make.width.mas_equalTo(kItemListHeight*4/3);
    }];
    [self.markView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.fileImgeView);
        make.width.height.mas_equalTo(44);
    }];
    [self.pauseImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.fileImgeView);
        make.width.height.mas_equalTo(24);
    }];
    [self.pauseBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.fileImgeView);
    }];
    [self.downCompleteImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(24);
        make.top.equalTo(self.fileImgeView.mas_top).offset(5);
        make.right.equalTo(self.contentView).offset(-15);
    }];
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.fileImgeView.mas_right).offset(10);
        make.top.equalTo(self.fileImgeView.mas_top).offset(5);
        make.right.equalTo(self.downCompleteImageView.mas_left).offset(-8);
    }];
    
    [self.progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.titleLabel.mas_left);
        make.centerY.equalTo(self.fileImgeView.mas_centerY);
        make.right.equalTo(self.contentView).offset(-5);
        make.height.mas_equalTo(2);
    }];
    [self.speedLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.progressView.mas_left);
        make.bottom.equalTo(self.fileImgeView.mas_bottom).offset(-5);
        make.height.mas_equalTo(18);
    }];
    [self.sizeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.progressView.mas_right);
        make.centerY.equalTo(self.speedLabel.mas_centerY);
        make.height.mas_equalTo(18);
    }];
}

- (void)bindViewModel:(HYFileDownloadItemViewModel *)vm
{
    if(!self.itemVM || self.itemVM != vm){
        self.itemVM = vm;
        if(vm.fileType){// 音频
            self.fileImgeView.backgroundColor = APPMainThemeColor;
            self.fileImgeView.image = nil;
            self.markView.hidden = NO;
        }else{//视频
            self.markView.hidden = YES;
            self.fileImgeView.backgroundColor = kClearColor;
            self.fileImgeView.image = [UIImage imageNamed:[HYFileManager videoImageSavePathWithFileName:vm.imageName]];
        }
        self.titleLabel.text = vm.fileName;
        self.progressView.hidden = NO;
        self.downCompleteImageView.hidden = YES;
        self.progressView.progress = vm.progress;
        if (vm.progress == 1) {
            self.downCompleteImageView.hidden = NO;
        }
        self.sizeLabel.text = vm.fileSize;
        @weakify(self);
        [[RACObserve(vm.downloadTask, status) takeUntil:self.rac_prepareForReuseSignal] subscribeNext:^(id x) {
            @strongify(self);
            switch ([x intValue]) {
                case HYDownloadStatus_Default:
                {
                    self.speedLabel.text = @"";
                    self.pauseBtn.userInteractionEnabled = YES;
                    self.progressView.hidden = NO;
                    self.downCompleteImageView.hidden = YES;
                }
                    break;
                case HYDownloadStatus_Error:
                {
                    self.pauseImgView.hidden = NO;
                    self.speedLabel.text = [NSString stringWithFormat:@"%@:%ld",NSLocalizedString(@"下载失败", nil),(long)self.errorCode];
                    self.pauseBtn.userInteractionEnabled = YES;
                    self.speedLabel.textColor = kRedColor;
                    self.downCompleteImageView.hidden = YES;
                }
                    break;
                case HYDownloadStatus_Waiting:
                {
                    self.pauseImgView.hidden = NO;
                    self.pauseBtn.userInteractionEnabled = YES;
                    self.speedLabel.textColor = kLightGrayColor;
                    self.speedLabel.text = NSLocalizedString(@"等待下载中", nil);
                    self.progressView.hidden = NO;
                    self.downCompleteImageView.hidden = YES;
                }
                    break;
                case HYDownloadStatus_Downloading:
                {
                    // 下载中
                    self.pauseImgView.hidden = YES;
                    self.pauseBtn.userInteractionEnabled = YES;
                    self.speedLabel.textColor = kLightGrayColor;
                    self.progressView.hidden = NO;
                    self.downCompleteImageView.hidden = YES;
                }
                    break;
                case HYDownloadStatus_Pause:
                {
                    self.pauseImgView.hidden = NO;
                    self.pauseBtn.userInteractionEnabled = YES;
                    self.speedLabel.text = NSLocalizedString(@"已暂停", nil);
                    self.speedLabel.textColor = kRedColor;
                    self.progressView.hidden = NO;
                    self.downCompleteImageView.hidden = YES;
                    [self.itemVM saveCurrentDownloadProgress:self.progress downloadSize:self.donwnloadSize];
                }
                    break;
                case HYDownloadStatus_Completed:
                {
                    self.pauseImgView.hidden = YES;
                    self.pauseBtn.userInteractionEnabled = NO;
                    self.progressView.progress = 1.0;
                    self.speedLabel.textColor = kLightGrayColor;
                    self.speedLabel.text = NSLocalizedString(@"已缓存", nil);
                    if(self.progress == 1.0){
                        self.downCompleteImageView.hidden = NO;
                        [self.itemVM downloadComplete:self.donwnloadSize];
                        [self.itemVM.filedownCompletdSubject sendNext:@"下载完成"];
                    }
                }
                    break;
                default:
                    break;
            }
        }];
        [vm.downloadTask setProgressReportBlock:^(HYBriefDownloadBaseTask *task, long long receivedBytes, long long totalBytes) {
            @strongify(self);
            self.progress = (CGFloat)receivedBytes*1.0/totalBytes;
            self.progressView.progress = self.progress;
            self.donwnloadSize = [NSString stringWithFormat:@"%@/%@",[CommUtls getSize:@(receivedBytes)],[CommUtls getSize:@(totalBytes)]];
            long long receivedTempBytes = receivedBytes - self.intervalFileSize;
            NSInteger intervals = [HYFileDownloadTool getIntervalsWithTimeStamp:self.lastSpeedTime];
            if (intervals >= 1 && receivedTempBytes>=0) {
                // 计算速度
                self.speedLabel.text = [NSString stringWithFormat:@"%@ / s", [HYFileDownloadTool stringFromByteCount:receivedTempBytes/intervals]];
                // 重置变量
                self.intervalFileSize = receivedBytes;
                self.lastSpeedTime = [HYFileDownloadTool getTimeStampWithDate:[NSDate date]];
            }
            if(self.progress == 1.0){
                self.donwnloadSize = [CommUtls getSize:@(totalBytes)];
            }
            self.sizeLabel.text = self.donwnloadSize;
        }];
        // 设置下载失败的回调
        [vm.downloadTask setFailureBlock:^(HYBriefDownloadBaseTask *task, NSError *error) {
            @strongify(self);
            // 弹窗提示
            self.errorCode = error.code;
            if (error.code == -999) {
                [HYHub showMessage:NSLocalizedString(@"下载取消", nil)];
            }else{
                [HYHub showMessage:[NSString stringWithFormat:@"%@:%ld",NSLocalizedString(@"下载失败", nil),(long)error.code]];
            }
        }];
    }
}

- (void)pauseBtnAction
{
    if(self.itemVM.downloadTask.status != HYDownloadStatus_Completed){
        [self.itemVM startOrPauseDownload];
    }
}

#pragma mark - loadLazy
- (UIImageView *)fileImgeView
{
    if(!_fileImgeView){
        _fileImgeView = [[UIImageView alloc]init];
        _fileImgeView.contentMode = UIViewContentModeScaleAspectFill;
        _fileImgeView.layer.cornerRadius = 4.0;
        _fileImgeView.layer.masksToBounds = YES;
    }
    return _fileImgeView;
}

- (UIImageView *)pauseImgView
{
    if(!_pauseImgView){
        _pauseImgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"icon_pause"]];
        _pauseImgView.hidden = YES;
    }
    return _pauseImgView;
}

- (UIImageView *)markView
{
    if(!_markView){
        if (@available(iOS 13.0, *)) {
            _markView = [[UIImageView alloc]initWithImage:[UIImage systemImageNamed:@"music.note"]];
        } else {
            _markView = [[UIImageView alloc]init];
        }
        _markView.hidden = YES;
    }
    return _markView;
}

- (UIImageView *)downCompleteImageView
{
    if(!_downCompleteImageView){
        _downCompleteImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"downComplete"]];
        _downCompleteImageView.hidden = YES;
    }
    return _downCompleteImageView;
}

- (UIButton *)pauseBtn
{
    if(!_pauseBtn){
        _pauseBtn = [[UIButton alloc]init];
        [_pauseBtn addTarget:self action:@selector(pauseBtnAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _pauseBtn;
}

- (UILabel *)titleLabel
{
    if(!_titleLabel){
        _titleLabel = [[UILabel alloc]init];
        _titleLabel.numberOfLines = 2;
        _titleLabel.lineBreakMode = NSLineBreakByCharWrapping;
        _titleLabel.textColor = APPTextThemeColor;
        _titleLabel.font = FONT_SIZE(14);
    }
    return _titleLabel;
}

- (UIProgressView *)progressView
{
    if(!_progressView){
        _progressView = [[UIProgressView alloc]initWithProgressViewStyle:UIProgressViewStyleDefault];
        _progressView.progressTintColor = APPMainThemeColor;
        _progressView.trackTintColor = UIColor.whiteColor;
    }
    return _progressView;
}

- (UILabel *)speedLabel
{
    if(!_speedLabel){
        _speedLabel = [[UILabel alloc]init];
        _speedLabel.textColor = kLightGrayColor;
        _speedLabel.font = FONT_SIZE(12);
    }
    return _speedLabel;
}

- (UILabel *)sizeLabel
{
    if(!_sizeLabel){
        _sizeLabel = [[UILabel alloc]init];
        _sizeLabel.textColor = kLightGrayColor;
        _sizeLabel.font = FONT_SIZE(12);
    }
    return _sizeLabel;
}

@end
